<template>
  <!-- 添加商品组件 -->
  <div class="add-goods">
    <!-- 头部路径导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 内容区 -->
    <el-card class="box-card">
      <el-row>
        <el-alert
          :title="noticeConfig.text"
          :style="noticeConfig.style"
          show-icon
          :closable="false"
        >
        </el-alert>
      </el-row>
      <!-- 步骤条 -->
      <el-row style="margin-top: 15px">
        <el-steps
          :space="200"
          :active="setpsActive"
          finish-status="success"
          align-center
        >
          <el-step title="基本信息"></el-step>
          <el-step title="商品参数"></el-step>
          <el-step title="商品属性"></el-step>
          <el-step title="商品图片"></el-step>
          <el-step title="商品内容"></el-step>
          <el-step title="完成"></el-step>
        </el-steps>
      </el-row>
      <!-- 各个内容面板 -->
      <el-row style="margin-top: 15px">
        <!-- 商品基本信息 -->
        <el-tabs
          :tab-position="'left'"
          style="height: 200px"
          :before-leave="switchTag"
          value="baseInfo"
        >
          <el-tab-pane label="基本信息" name="baseInfo">
            <el-form
              :model="addGoodsConfig.baseInfo"
              :rules="addGoodsConfig.baseInfoRules"
              ref="baseInfoForm"
              label-width="100px"
              label-position="top"
              class="demo-ruleForm"
              style="width: 100%"
            >
              <el-form-item label="商品名称：" prop="name">
                <el-input
                  v-model.trim="addGoodsConfig.baseInfo.name"
                ></el-input>
              </el-form-item>
              <el-form-item label="商品价格：" prop="price">
                <el-input
                  v-model.trim="addGoodsConfig.baseInfo.price"
                ></el-input>
              </el-form-item>
              <el-form-item label="商品重量：" prop="weight">
                <el-input
                  v-model.trim="addGoodsConfig.baseInfo.weight"
                ></el-input>
              </el-form-item>
              <el-form-item label="商品数量：" prop="num">
                <el-input
                  v-model.number="addGoodsConfig.baseInfo.num"
                ></el-input>
              </el-form-item>
              <el-form-item label="商品分类：" prop="category">
                <el-cascader
                  v-model="addGoodsConfig.baseInfo.category"
                  @change="queryFlag = true"
                  :options="addGoodsConfig.baseInfo.categoryList"
                  :props="addGoodsConfig.baseInfo.casProps"
                  ref="addCatCascader"
                  clearable
                  popper-class="cat-cascader"
                >
                </el-cascader>
              </el-form-item>
            </el-form>
          </el-tab-pane>
          <el-tab-pane label="商品参数" name="params" :lazy="true">
            <div
              style="margin-top: 20px"
              v-for="item in addGoodsConfig.baseInfo.params"
              :key="item.attr_id"
            >
              <el-row v-if="item.attr_vals.length > 0">
                {{ item.attr_name }}
              </el-row>
              <el-row v-if="item.attr_vals.length > 0" style="margin-top: 20px">
                <el-checkbox
                  v-for="(item2, index) in item.attr_vals"
                  :key="index"
                  v-model="item2.bool"
                  :label="item2.value"
                  border
                  size="medium"
                  style="margin-bottom: 10px"
                ></el-checkbox>
              </el-row>
            </div>
          </el-tab-pane>
          <el-tab-pane label="商品属性" name="attr" :lazy="true">
            <el-form>
              <el-form-item
                :label="item.attr_name"
                v-for="item in addGoodsConfig.baseInfo.attrs"
                :key="item.attr_id"
              >
                <el-input v-model.trim="item.attr_vals"></el-input>
              </el-form-item>
            </el-form>
          </el-tab-pane>
          <el-tab-pane label="商品图片" name="img" :lazy="true">
            <el-upload
              action="http://127.0.0.1:8888/api/private/v1/upload"
              :headers="{ Authorization: token }"
              ref="upload"
              accept=".png,.jpg"
              list-type="picture-card"
              :on-preview="handlePictureCardPreview"
              :on-remove="handleRemove"
              :auto-upload="true"
            >
              <i class="el-icon-plus"></i>
            </el-upload>
            <el-dialog :visible.sync="addGoodsConfig.dialogImageVisible">
              <img width="100%" :src="addGoodsConfig.dialogImageUrl" alt="" />
            </el-dialog>
          </el-tab-pane>
          <el-tab-pane label="商品内容" name="content" :lazy="true">
            <vue-tinymce
              v-model="tinymceConfig.content"
              :setting="tinymceConfig.setting"
            />
            <el-row style="margin-top: 20px">
              <el-button type="primary" @click="addGoodsSubmit()"
                >添加商品</el-button
              >
            </el-row>
          </el-tab-pane>
        </el-tabs>
      </el-row>
    </el-card>
  </div>
</template>

<script>
//价格验证
var checkPrice = (rule, value, callback) => {
  if (isNaN(value) || value <= 0) {
    callback(new Error("请输入正确的价格"));
  } else {
    callback();
  }
};

//商品重量验证
var checkWeight = (rule, value, callback) => {
  if (isNaN(value) || value < 0) {
    callback(new Error("请输入正确的重量"));
  } else {
    callback();
  }
};

//商品数量验证
var checkNum = (rule, value, callback) => {
  if (isNaN(value) || value <= 0 || parseInt(value) != value) {
    callback(new Error("请输入正确的数量"));
  } else {
    callback();
  }
};

//分类验证
var checkCategory = (rule, value, callback) => {
  if (!value) {
    callback(new Error("请选择分类"));
  } else {
    if (value.length < 3) {
      callback(new Error("只能选择三级分类"));
    } else {
      callback();
    }
  }
};

export default {
  data() {
    return {
      //token
      token: localStorage.getItem("token"),
      //加载层参数配置
      loadingConfig: {
        target: "body",
        fullscreen: true,
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.1)",
        text: "拼命加载中",
      },
      //头部消息提示条配置
      noticeConfig: {
        //文字
        text: "添加商品信息",
        //样式
        style: {
          //字体颜色
          color: "#909399",
          //字体大小
          fontSize: "13px",
          //内容行高
          lineHeight: "21px",
          display: "flex",
          justifyContent: "center",
          //背景颜色
          backgroundColor: "#F4F4F5",
        },
      },
      //步骤条序号
      setpsActive: 0,
      //商品参数属性请求控制
      queryFlag: true,
      //添加商品配置
      addGoodsConfig: {
        //基本信息
        baseInfo: {
          //商品名称
          name: "",
          //商品价格
          price: 0,
          //商品重量
          weight: 0,
          //商品数量
          num: 0,
          //选中的商品分类
          category: [],
          //分类列表
          categoryList: [],
          //参数列表
          params: [],
          //属性列表
          attrs: [],
          //级联菜单属性
          casProps: {
            expandTrigger: "hover",
            value: "cat_id",
            label: "cat_name",
          },
        },
        //上传图片配置
        dialogImageUrl: "",
        dialogImageVisible: false,
        //基本信息验证规则
        baseInfoRules: {
          name: [
            { required: true, message: "请输入商品名称", trigger: "blur" },
            {
              min: 1,
              max: 255,
              message: "商品名称长度在 1 到 255 个字符",
              trigger: "blur",
            },
          ],
          price: [
            { validator: checkPrice, trigger: "change" },
            { required: true, message: "请输入商品价格", trigger: "change" },
          ],
          weight: [
            { validator: checkWeight, trigger: "change" },
            { required: true, message: "请输入商品重量", trigger: "change" },
          ],
          num: [
            { validator: checkNum, trigger: "change" },
            { required: true, message: "请输入商品数量", trigger: "change" },
          ],
          category: [
            { validator: checkCategory, trigger: "change" },
            { required: true, message: "请选择商品分类", trigger: "change" },
          ],
        },
      },
      //富文本编辑器配置
      tinymceConfig: {
        content: "",
        setting: {
          toolbar:
            "undo redo bold italic underline strikethrough forecolor backcolor fontselect fontsizeselect   formatselect alignleft aligncenter alignright alignjustify  link unlink  numlist bullist  image media table    indent outdent  superscript subscript  removeformat fullscreen",

          plugins: "link image media table lists fullscreen quickbars",
          language: "zh_CN", //本地化设置
          height: 350,
          branding: false,
          resize: false,
          auto_focus: true,
          toolbar_mode: "wrap",
          elementpath: false,
          statusbar: false,
          menubar: false,
          toolbar_drawer: false,
        },
      },
    };
  },
  methods: {
    getCategoryList() {
      //获取商品分类列表
      //发起请求
      this.$axios
        .get("/categories", {
          params: {
            type: [1, 2, 3],
          },
        })
        .then((res) => {
          if (res.meta.status == 200) {
            //设置分类列表数据
            this.addGoodsConfig.baseInfo.categoryList = res.data;
          } else {
            //提示错误信息
            this.$message.error(res.meta.msg);
          }
        })
        .catch((error) => {
          this.$message.error(error);
        });
    },
    switchTag(activeName, oldActiveName) {
      console.log(activeName);
      console.log(oldActiveName);
      var flag = true;
      if (oldActiveName == "baseInfo" && activeName != "baseInfo") {
        this.$refs["baseInfoForm"].validate((valid) => {
          if (!valid) {
            flag = false;
          }
        });
      }
      if (!flag) {
        this.$message.error("请先完善基本信息");
        return false;
      }
      if (this.addGoodsConfig.baseInfo.category.length < 3) {
        this.$message.error("只能选择三级分类");
        return false;
      }
      if (oldActiveName == "baseInfo" && this.queryFlag) {
        this.getParams("many");
        this.getParams("only");
        this.queryFlag = false;
      }
      switch (activeName) {
        case "baseInfo":
          this.setpsActive = 0;
          break;
        case "params":
          this.setpsActive = 1;
          break;
        case "attr":
          this.setpsActive = 2;
          break;
        case "img":
          this.setpsActive = 3;
          break;
        case "content":
          this.setpsActive = 4;
          break;
        default:
          break;
      }
    },
    getParams(type) {
      //根据分类ID查询参数
      var id = this.addGoodsConfig.baseInfo.category[
        this.addGoodsConfig.baseInfo.category.length - 1
      ];
      //发起请求
      this.$axios
        .get("/categories/" + id + "/attributes", {
          params: {
            sel: type,
          },
        })
        .then((res) => {
          if (res.meta.status == 200) {
            if (type == "many") {
              //处理数据
              res.data.forEach((item) => {
                if (item.attr_vals) {
                  item.attr_vals = item.attr_vals.split(",");
                  if (item.attr_vals.length > 0) {
                    item.attr_vals.forEach((item2, index) => {
                      item.attr_vals[index] = {
                        value: item2,
                        bool: true,
                      };
                    });
                  }
                }
              });
              this.addGoodsConfig.baseInfo.params = res.data;
            } else if (type == "only") {
              //处理数据
              //   res.data.forEach((item) => {
              //     if (item.attr_vals) {
              //       item.attr_vals = item.attr_vals.split(",");
              //     }
              //   });
              this.addGoodsConfig.baseInfo.attrs = res.data;
            }
          } else {
            //提示错误信息
            this.$message.error(res.meta.msg);
          }
        })
        .catch((error) => {
          this.$message.error(error);
        });
    },
    handleRemove(file, fileList) {
      console.log(file, fileList);
      console.log(this.$refs["upload"]);
    },
    handlePictureCardPreview(file) {
      this.addGoodsConfig.dialogImageUrl = file.url;
      this.addGoodsConfig.dialogImageVisible = true;
    },
    addGoodsSubmit() {
      //添加商品提交
      this.setpsActive = 5;
      //打开加载层
      var loading = this.$loading.service(this.loadingConfig);
      // 获取上传图片组
      var picsArr = [];
      if (this.$refs["upload"].uploadFiles.length > 0) {
        this.$refs["upload"].uploadFiles.forEach((item) => {
          if (item.response.meta.status == 200) {
            picsArr.push({
              pic: item.response.data.tmp_path,
            });
          }
        });
      }
      //获取动态参数和静态属性
      var attrs = [];
      if (this.addGoodsConfig.baseInfo.attrs.length > 0) {
        this.addGoodsConfig.baseInfo.attrs.forEach((item) => {
          if (item.attr_vals.trim()) {
            attrs.push({
              attr_id: item.attr_id,
              attr_value: item.attr_vals,
            });
          }
        });
      }
      if (this.addGoodsConfig.baseInfo.params.length > 0) {
        this.addGoodsConfig.baseInfo.params.forEach((item) => {
          if (item.attr_vals.length > 0) {
            item.attr_vals.forEach((item2) => {
              if (item2.bool) {
                attrs.push({
                  attr_id: item.attr_id,
                  attr_value: item2.value,
                });
              }
            });
          }
        });
      }
      //发起请求
      this.$axios
        .post("/goods", {
          goods_name: this.addGoodsConfig.baseInfo.name,
          goods_cat: this.addGoodsConfig.baseInfo.category.join(","),
          goods_price: parseFloat(this.addGoodsConfig.baseInfo.price),
          goods_number: parseInt(this.addGoodsConfig.baseInfo.num),
          goods_weight: parseFloat(this.addGoodsConfig.baseInfo.weight),
          goods_introduce: this.tinymceConfig.content,
          pics: picsArr,
          attrs: attrs,
        })
        .then((res) => {
          if (res.meta.status == 201) {
            this.setpsActive = 6;
            //提示成功信息
            this.$message.success(res.meta.msg);
            //跳转路由
            this.$emit("go-route", "/goods");
          } else {
            //提示错误信息
            this.$message.error(res.meta.msg);
          }
        })
        .catch((error) => {
          //请求失败
          this.$message.error(error);
        })
        .finally(() => {
          //关闭加载层
          this.$nextTick(() => {
            loading.close();
          });
        });
    },
  },
  mounted() {
    this.getCategoryList();
  },
};
</script>

<style lang="less" scoped>
::v-deep .el-card {
  height: auto;
  overflow: auto;
  .el-tabs--left {
    height: auto !important;
  }
}
</style>
<style lang="less">
.add-goods {
  .el-steps {
    .el-step__title {
      font-size: 12px !important;
    }
  }
}
</style>